"""

应用joblib实现模型的保存与加载

当训练或者计算好一个模型之后，那么如果别人需要我们的模型进行结果预测，就需要保存模型（主要是保存算法的参数）
保存完模型就不需要每次都进行训练数据。

sklearn模型的保存和加载API
    from sklearn.externals import joblib 或 import joblib
    保存：
        def dump(value, filename, compress=0, protocol=None, cache_size=None):
            value: any Python object The object to store to disk.
        joblib.dump(rf, 'test.pkl')
    加载：estimator = joblib.load('test.pkl')
"""
from sklearn.datasets import fetch_california_housing
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.preprocessing import StandardScaler
import joblib

def model_save():
    # 1 获取数据集
    house_data = fetch_california_housing(data_home="./data")
    # 2数据预处理
    # 划分特征值和目标值
    x = house_data.get("data")
    y = house_data.get("target")
    # 训练集和测试集划分
    x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=22)

    # 3 特征工程
    transfer = StandardScaler()
    x_train = transfer.fit_transform(x_train)
    x_test = transfer.transform(x_test)

    # 4 算法训练-模型
    estimator = Ridge()
    super_param = {"alpha": [0.0, 0.5, 1.0, 3.0, 5.0], "max_iter": [2000, 4000, 6000, 8000, 10000]}
    estimator = GridSearchCV(estimator=estimator, param_grid=super_param, cv=10)
    estimator.fit(x_train, y_train)

    # 5 得出模型
    # print("岭回归-权重系数为：\n", estimator.coef_)
    # print("岭回归-偏置为：\n", estimator.intercept_)

    # 6 模型评估
    y_predict = estimator.predict(x_test)
    # 0.6129627045248398
    print("准确率：", estimator.score(x_test, y_test))
    error = mean_squared_error(y_test, y_predict)
    # 0.49182311234443526
    print("岭回归误差：", error)

    # 7 模型保存
    joblib.dump(estimator,filename='./model/house_price_predict.pkl')

def model_load():
    # 1 获取数据集
    house_data = fetch_california_housing(data_home="./data")
    # 2数据预处理
    # 划分特征值和目标值
    x = house_data.get("data")
    y = house_data.get("target")
    # 训练集和测试集划分
    x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=22)

    # 3 特征工程
    transfer = StandardScaler()
    x_train = transfer.fit_transform(x_train)
    x_test = transfer.transform(x_test)

    # 4 模型加载
    estimator = joblib.load('./model/house_price_predict.pkl')

    # 5 模型评估
    y_predict = estimator.predict(x_test)
    # 0.6129627045248398
    print("准确率：", estimator.score(x_test, y_test))
    error = mean_squared_error(y_test, y_predict)
    # 0.49182311234443526
    print("岭回归误差：", error)


if __name__ == '__main__':
    # model_save()

    model_load()